// pages/cart/index.js
import {openSetting,getSetting,chooseAddress,showModal,showToast} from "../../utils/youHuaWxAPI.js";
import regeneratorRuntime from "../../lib/runtime/runtime";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: {},
    cart: [],
    allChecked: false,
    totalNum: 0,
    totalPrice: 0
  },

  onShow: function () {
    // 获取缓存中的用户获货地址
    const address = wx.getStorageSync("address");
    // 更新本地数据
    this.setData({address});    
    // 获取缓存中用户的购物车信息
    const cart = wx.getStorageSync("cart") || [];
    this.flushCart(cart);
  },

  // 处理点击添加收货地址按钮
  async dealChooseAddress() {
    try 
    {
      // 获取用户授予小程序的权限
      const res = await getSetting();
      const scopeAddress = res.authSetting["scope.address"];
      // 如果用户没授权地址信息 诱导用户开启授权
      if (scopeAddress === false) 
      {
        const flag = await openSetting();     
      }
      // 获取用户地址
      let address = await chooseAddress();
      address.detailAddress = address.provinceName + address.cityName + address.countyName + address.detailInfo;
      // 将用户地址保存到本地缓存中
      wx.setStorageSync("address", address);
      // console.log(address);
    }
    catch(err) 
    {
      console.log(err);
    }
  },

  // 更新购物车的数据  包含  全选  总数目  总价格 更新缓存
  flushCart(cart) {
    let allChecked = true;
    // 获取商品总数目和总价格
    // 获取商品总价格
    let totalNum = 0;
    let totalPrice = 0;
    if (cart.length) {
      cart.forEach(v => {
        if (v.checked) {
          totalNum += v.num;
          totalPrice += v.num * v.goods_price;
        }
        else allChecked = false;
      });
    }
    else allChecked = false;

    // 更新本地数据
    this.setData({cart,allChecked,totalNum,totalPrice});
    // 更新缓存数据
    wx.setStorageSync("cart",cart);
  },

  // 处理商品复选框状态的改变
  handleSwitch(e) {
    // console.log(e);
    const goods_id = e.currentTarget.dataset.goods_id;
    let cart = this.data.cart;
    const index = cart.findIndex(v =>  v.goods_id === goods_id);
    cart[index].checked = !cart[index].checked;
    this.flushCart(cart);
  },
  // 处理全选复选框的状态改变
  handleAllChecked() {
    let allChecked = !this.data.allChecked;
    const cart = this.data.cart;
    cart.forEach(v => {
      v.checked = allChecked;
    });
    this.flushCart(cart);
  },

  // 处理商品数量的变更
  async handleGoodsNumChange(e) {
    try 
    {
      const {goods_id,operator} = e.currentTarget.dataset;
      const {cart} = this.data;
      const index = cart.findIndex(v => v.goods_id === goods_id);
      // 商品数量为 1 且用户点击减少数量按钮
      if (cart[index].num === 1 && operator === -1) 
      {
        let res = await showModal({content: "您要删除该商品？"});
        if(res.confirm) 
        {
          cart.splice(index,1);
          this.flushCart(cart);
        }     
        return;
      }
      cart[index].num += operator;
      this.flushCart(cart);
    } catch(err) {
      console.log(err);
    }
  },


  // 处理结算按钮的点击 
  async handlePay() {
    const {address,totalNum} = this.data;
    // 用户是否添加地址
    if (!address.userName) {
      await showToast({title: "请添加收货地址！"});
      return;
    }
    // 用户购物车是否有商品
    if (totalNum === 0) {
      await showToast({title: "请添加商品！"});
      return;
    }
    // 以上条件都满足则前往支付页面
    wx.navigateTo({
      url: '/pages/pay/index'
    });
  }

})